import { Component, OnInit, ViewChild, Injector, AfterViewInit, ViewEncapsulation, ElementRef } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { SelectItem } from 'primeng/api';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent, FileUpload } from 'primeng/primeng';
import { TechFileServiceProxy, FileRecordListDto,FileRecordServiceProxy, TechFileOutServiceProxy, BorrowTechFileDto, AtionState, TechFileState, ComboboxItemDto, TechFileInfoServiceProxy } from '@shared/service-proxies/service-proxies';
import * as moment from 'moment';
import { BsDatepickerViewMode } from 'ngx-bootstrap/datepicker/models';
import { BsDatepickerConfig, BsDaterangepickerConfig } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import * as G2 from '@antv/g2';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import { AppConsts } from '@shared/AppConsts';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-borrowtechfile',
  templateUrl: './borrowtechfile.component.html',
  styleUrls: ['./borrowtechfile.component.css'],
  animations: [appModuleAnimation()]
})
export class BorrowtechfileComponent extends AppComponentBase  implements OnInit {


  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('paginatorNormal') paginatorNormal: Paginator;
  @ViewChild('paginatorSpecial') paginatorSpecial: Paginator;
  @ViewChild('paginatorRecover') paginatorRecover: Paginator;
  @ViewChild('paginatorFileRecor') paginatorFileRecor: Paginator;
  @ViewChild('dataTableNormalProductions') dataTableNormalProductions: Table;
  @ViewChild('dataTableSpecialProductions') dataTableSpecialProductions: Table;
  @ViewChild('dataTableRecoverProductions') dataTableRecoverProductions: Table;
  @ViewChild('dataTableFileRecordProductions') dataTableFileRecordlProductions: Table;
  @ViewChild('ExcelFileUpload') excelFileUpload: FileUpload;
  @ViewChild('techFileInfoTypeCombobox') techFileInfoTypeCombobox: ElementRef;
  @ViewChild('securityTypeCombobox') securityTypeCombobox: ElementRef;
  @ViewChild('stageTypeCombobox') stageTypeCombobox: ElementRef;
  advancedFiltersAreShown: Boolean = false;
  uploadUrl: string;

  primengTableHelperNormalProductions = new PrimengTableHelper();
  primengTableHelperSpecialProductions = new PrimengTableHelper();
  primengTableFileRecordProductions = new PrimengTableHelper();
  primengTableRecoverProductions = new PrimengTableHelper();
  

  emptyText=" ";
  displayBasic: boolean;   
  boor = new BorrowTechFileDto();
  stages: Array<ComboboxItemDto> = new Array<ComboboxItemDto>();
  securitys: Array<ComboboxItemDto> = new Array<ComboboxItemDto>();
  filetypes: Array<ComboboxItemDto> = new Array<ComboboxItemDto>();
  stage=0;
  security=0;
  filetype=0;
  filterText = '';
  selectedProducts: any[];
  selectedProductsgh: any[];
  constructor(
    injector: Injector, 
    private _fileRecordServiceProxy: FileRecordServiceProxy,
    private _techFileOutServiceProxy: TechFileOutServiceProxy,
    private _techfileServiceProxy: TechFileInfoServiceProxy,
    private _httpClient: HttpClient,
  ) {
    super(injector);
    this.uploadUrl = AppConsts.remoteServiceBaseUrl + '/LaborHourLib/ImportLibForLaborHourExcel';
  }

  ngOnInit(): void {
    this.getstage();
    this.getsecurity();
    this.getfiletype();
  }

 
  getstage() {
    this._techfileServiceProxy.getComboboxItemForStageType().subscribe(result => {
      this.stages = result;
      setTimeout(() => {

        $(this.stageTypeCombobox.nativeElement).selectpicker('refresh');
        
      });
    });
  }

  getsecurity() {
    this._techfileServiceProxy.getComboboxItemForSecurityType().subscribe(result => {
      this.securitys = result;
      setTimeout(() => {


        $(this.securityTypeCombobox.nativeElement).selectpicker('refresh');
      });
    });
  }

  getfiletype() {
    this._techfileServiceProxy.getComboboxItemForTechFileInfoType().subscribe(result => {
      this.filetypes = result;
      setTimeout(() => {

        $(this.techFileInfoTypeCombobox.nativeElement).selectpicker('refresh');
        
      });
    });
  }



  getFileRecord(id :string,event?: LazyLoadEvent) {
    
    this.primengTableFileRecordProductions.showLoadingIndicator(); 
    this._fileRecordServiceProxy.getFileRecord( 
      id
    )
      .subscribe((result) => { 
        this.primengTableFileRecordProductions.records = result; 
      });
  }
 

  getNormalProduction(event?: LazyLoadEvent) {
    this.primengTableHelperNormalProductions.showLoadingIndicator();
    if (this.primengTableHelperNormalProductions.shouldResetPaging(event)) {
      this.paginatorNormal.changePage(0);
      return;
    }
    this.primengTableHelperNormalProductions.showLoadingIndicator(); 
    this._techFileOutServiceProxy.getTechFileAll(
      this.filetype==0?undefined:this.filetype,
      this.stage==0?undefined:this.stage,
      this.security==0?undefined:this.security,
      this.filterText,
      this.primengTableHelperNormalProductions.getSorting(this.dataTableNormalProductions),
      this.primengTableHelperNormalProductions.getMaxResultCount(this.paginatorNormal, event),
      this.primengTableHelperNormalProductions.getSkipCount(this.paginatorNormal, event)
    )
      .subscribe((result) => {
        this.primengTableHelperNormalProductions.totalRecordsCount = result.totalCount;
        this.primengTableHelperNormalProductions.records = result.items;
        this.primengTableHelperNormalProductions.hideLoadingIndicator();
      });
  }


  getSpecialProduction(event?: LazyLoadEvent) { 
    if (this.primengTableHelperSpecialProductions.shouldResetPaging(event)) {
      this.paginatorSpecial.changePage(0);

      return;
    }
    this.primengTableHelperSpecialProductions.showLoadingIndicator();

    this._techFileOutServiceProxy.getTechFileForBorrow(
      this.filetype==0?undefined:this.filetype,
      this.stage==0?undefined:this.stage,
      this.security==0?undefined:this.security,
      this.filterText,
      this.primengTableHelperSpecialProductions.getSorting(this.dataTableSpecialProductions),
      this.primengTableHelperSpecialProductions.getMaxResultCount(this.paginatorSpecial, event),
      this.primengTableHelperSpecialProductions.getSkipCount(this.paginatorSpecial, event)
    )
      .subscribe((result) => {
        this.primengTableHelperSpecialProductions.totalRecordsCount = result.totalCount;
        this.primengTableHelperSpecialProductions.records = result.items;
        this.primengTableHelperSpecialProductions.hideLoadingIndicator();

      });
  }

  getrecover(event?: LazyLoadEvent) { 
    if (this.primengTableRecoverProductions.shouldResetPaging(event)) {
      this.paginatorRecover.changePage(0);

      return;
    }
    this.primengTableRecoverProductions.showLoadingIndicator();

    this._techFileOutServiceProxy.getTechFileForRecover(
      this.filetype==0?undefined:this.filetype,
      this.stage==0?undefined:this.stage,
      this.security==0?undefined:this.security,
      this.filterText,
      this.primengTableRecoverProductions.getSorting(this.dataTableRecoverProductions),
      this.primengTableRecoverProductions.getMaxResultCount(this.paginatorRecover, event),
      this.primengTableRecoverProductions.getSkipCount(this.paginatorRecover, event)
    )
      .subscribe((result) => {
        this.primengTableRecoverProductions.totalRecordsCount = result.totalCount;
        this.primengTableRecoverProductions.records = result.items;
        this.primengTableRecoverProductions.hideLoadingIndicator();

      });
  }


  reloadPage(): void {
    this.paginatorNormal.changePage(this.paginatorNormal.getPage());
    this.paginatorSpecial.changePage(this.paginatorSpecial.getPage());
    this.paginatorRecover.changePage(this.paginatorRecover.getPage());
    this.selectedProducts = [];
    this.selectedProductsgh = [];
  }
  borrowfile(id :string): void
  { 
    this.boor.ids=  new Array<string>(id);
    this.boor.ation=AtionState.借出;
    this.boor.state=TechFileState.借出中;
    this._techFileOutServiceProxy.borrowTechFile(
      this.boor
    ) .subscribe((result) => { 
      this.reloadPage();
    }); 
  }

  returnfile(id :string)
  { 
    this.boor.ids=  new Array<string>(id);
    this.boor.ation=AtionState.归还;
    this.boor.state=TechFileState.归还中;
    this._techFileOutServiceProxy.borrowTechFile(
      this.boor
    ).subscribe((result) => { 
      this.reloadPage();
    }); 
  }

  SelectedTechfilecancel(): void { 
    let selectedidsgh = new Array<string>();
    for (let index = 0; index < this.selectedProductsgh.length; index++) {
      selectedidsgh.push(this.selectedProductsgh[index].id);
    }
    let boorgh = new BorrowTechFileDto();
    boorgh.ids = selectedidsgh;
    boorgh.state = TechFileState.借出; //取消归还的上一个状态为借出或待归还
    boorgh.ation = AtionState.归还;
    this._techFileOutServiceProxy.refuseTechFileAll(
      boorgh
    ).subscribe((result) => {
  
      this.reloadPage();
    });
  }
  
  techfilecancel(id: string): void { 
    this.boor.ids=  new Array<string>(id);
    this.boor.state = TechFileState.借出; //取消归还的上一个状态为借出或待归还
    this.boor.ation = AtionState.归还;   
    this._techFileOutServiceProxy.refuseTechFile(
      this.boor
    ).subscribe((result) => {

      this.reloadPage();
    });

  } 

  SelectedTechfilejy() { 
    let selectedids = new Array<string>();
    for (let index = 0; index < this.selectedProducts.length; index++) {
    if(this.selectedProducts[index].status!=TechFileState.正常)
    {
        this.message.warn("只能借出正常状态的文件！","借出失败！");
        return;
    }
      selectedids.push(this.selectedProducts[index].id);
    }
    let boorjy = new BorrowTechFileDto();
    boorjy.ids = selectedids;
    boorjy.ation=AtionState.借出;
    boorjy.state=TechFileState.借出中;
    this._techFileOutServiceProxy.borrowTechFileAll(
      boorjy
    ).subscribe((result) => {
  
      this.reloadPage();
    });
  }

  SelectedTechfilegh() { 
    let selectedidsgh = new Array<string>();
    for (let index = 0; index < this.selectedProductsgh.length; index++) {
      if(this.selectedProductsgh[index].status!=TechFileState.借出 && this.selectedProductsgh[index].status!=TechFileState.待归还)
    {
        this.message.warn("只能归还借出，待归还状态的文件！","归还失败！");
        return;
    }
      selectedidsgh.push(this.selectedProductsgh[index].id);
    }
    let boorgh = new BorrowTechFileDto();
    boorgh.ids = selectedidsgh;
    boorgh.ation=AtionState.归还;
    boorgh.state=TechFileState.归还中;
    this._techFileOutServiceProxy.borrowTechFileAll(
      boorgh
    ).subscribe((result) => {
  
      this.reloadPage();
    });
  }


  // recoverfile(id :string): void
  // { 
  //   this.boor.id=id;
  //   this.boor.ation=AtionState.归还;
  //   this.boor.state=TechFileState.待更新;
  //   this._techFileOutServiceProxy.borrowTechFile(
  //     this.boor
  //   ) .subscribe((result) => { 
  //     this.reloadPage();
  //   }); 
  // }
  
  // deleteProduction(production: ProductionOutput): void {
  //   this.message.confirm(
  //     '删除【' + production.id + '】,图号：' + production.picNo + '的零件定额',
  //     this.l('AreYouSure'),
  //     (isConfirmed) => {
  //       if (isConfirmed) {
  //         this._libraryOfLaborServiceProxy.deleteProduction(production.id)
  //           .subscribe(() => {
  //             this.reloadPage();
  //             this.notify.success(this.l('SuccessfullyDeleted'));
  //           });
  //       }
  //     }
  //   );
  // }

  uploadExcel(data: { files: File }): void {
    this.primengTableHelperNormalProductions.showLoadingIndicator();

    const formData: FormData = new FormData();
    const file = data.files[0];
    formData.append('file', file, file.name);
    this._httpClient
      .post<any>(this.uploadUrl, formData)
      .pipe(finalize(() => this.excelFileUpload.clear()))
      .subscribe(response => {
        this.primengTableHelperNormalProductions.hideLoadingIndicator();

        if (response.success) {
          this.message.success('导入Excel成功');

          //this.importSalaryDtoList.salaryList = this.salary;
        } else if (response.error != null) {
          this.message.error('导入Excel失败');
        }

      });
  }

  onUploadExcelError(): void {
    this.primengTableHelperNormalProductions.hideLoadingIndicator();
    this.notify.error('上传失败');
  }

  showPositionDialog(id :string,event?: LazyLoadEvent) { 
    this.displayBasic = true;
    this.getFileRecord(id,event)
}
 
 }